<template>
  <div>
    <el-form
      :model="spuFormData"
      class="spuUpdate_form"
      ref="spuUpdateFormRef"
      label-width="100"
    >
      <el-form-item label="SPU名称">
        <el-input v-model="spuFormData.spuName" placeholder="请输入SPU名称" />
      </el-form-item>
      <el-form-item label="SPU品牌">
        <!-- v-model="key_first"
          @change="SELECT_CHANGE($event, 2)" -->
        <el-select
          placeholder="请选择SPU品牌"
          clearable
          style="width: 200px"
          v-model="spuFormData.tmId"
        >
          <template v-for="item in trademark_list" :key="item.id">
            <el-option :label="item.tmName" :value="item.id" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="spuFormData.description"
          placeholder="请输入SPU描述"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="SPU照片">
        <el-upload
          v-model:file-list="fileList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="uploadCallback"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="SPU销售属性">
        <div class="table_section" style="width: 100%">
          <div class="header">
            <el-select
              :placeholder="
                select_saleAttr_length
                  ? `请选择${select_saleAttr_length}个销售属性`
                  : '无'
              "
              clearable
              style="width: 200px"
              v-model="select_saleAttrIdd"
            >
              <template v-for="item in saleattr_list" :key="item.id">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-if="item.isShow"
                />
              </template>
            </el-select>

            <el-button
              type="primary"
              size="default"
              icon="Plus"
              @click="ADD_ATTR_ROW()"
              :disabled="select_saleAttr_length == 0"
              style="margin-left: 10px"
            >
              添加销售属性
            </el-button>
          </div>
          <div class="table" style="margin-top: 10px">
            <el-table :data="spuFormData.spuSaleAttrList" stripe border>
              <el-table-column
                label="序号"
                width="100"
                type="index"
                align="center"
              />
              <el-table-column prop="saleAttrName" label="属性名" width="100" />

              <el-table-column
                prop="supSaleAttrValueList"
                label="属性值"
                min-width="400"
              >
                <template #default="{ row, $index }">
                  <div class="tag_row">
                    <el-tag
                      v-for="(tag, tag_i) in row.supSaleAttrValueList"
                      :key="tag_i"
                      style="margin: 5px"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(row.supSaleAttrValueList, tag_i)"
                    >
                      {{ tag.saleAttrValueName }}
                    </el-tag>
                    <el-input
                      v-if="row.selected"
                      :ref="(el) => (InputRef[$index] = el)"
                      v-model="inputValue"
                      style="width: 80px"
                      size="small"
                      @keyup.enter="handleInputConfirm(row, $index)"
                      @blur="handleInputConfirm(row, $index)"
                    />
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(row, $index)"
                    >
                      + New Tag
                    </el-button>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="操作" fixed="right" width="100">
                <template #default="{ row, $index }">
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    @click="DELETE_ATTR(row, $index)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="save_btns" style="margin-top: 10px">
              <el-button type="primary" size="default" @click="confirmClick">
                保存
              </el-button>

              <el-button size="default" @click="cancelClick">取消</el-button>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: 'spuUpdate',
}
</script>
<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import {
  resAllTrademark,
  resAllSaleAttr,
  resIdBySpuImgList,
  resIdBySpuAttrList,
  reqAddOrUpdateSPU,
} from '@/api/product'
import type { Spu, Records } from '@/api/product/type'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { publicConfirm } from '@/utils/handleData'
const props = defineProps(['formType', 'updateData'])

watch(
  () => props.formType,
  (newValue, oldValue) => {
    if (newValue == 'ADD_SPU' || newValue == 'EDIT_SPU') {
      Object.assign(spuFormData, props.updateData)
      initUpdateData()
      console.log('updateSPU', newValue, oldValue)
    }
  },
  { deep: true },
)

const emit = defineEmits(['cancelUpdate', 'confirmUpdate'])

let trademark_list = ref<Records>([])
let saleattr_list = ref<any>([])
let select_saleAttrIdd = ref()
let select_saleAttr_length = ref(0)

const spuFormData_init = {
  id: '',
  spuName: '',
  description: '',
  category: '',
  category3Id: '',
  tmId: '',
  spuSaleAttrList: [],
  spuImageList: [],
}
const spuFormData = reactive<Spu>({ ...spuFormData_init })

const initUpdateData = async () => {
  let id: any = spuFormData.id
  if (id > 0) {
    let result: any = await resIdBySpuImgList(id)
    if (result.code == 200) {
      // spuFormData.spuImageList = res.data
      initFileList(result.data)
    }

    let result1: any = await resIdBySpuAttrList(id)

    if (result1.code == 200) {
      spuFormData.spuSaleAttrList = result1.data.map((item) => {
        item['selected'] = false
        return item
      })
    }
  }

  let result2: any = await resAllTrademark(id)
  if (result2.code == 200) {
    trademark_list.value = result2.data
  }

  let result3: any = await resAllSaleAttr(id)
  if (result3.code == 200) {
    saleattr_list.value = result3.data.map((item) => {
      item['isShow'] = true
      return item
    })
    initSaleAttrList()
  }
}
const initSaleAttrList = () => {
  let length = 0
  saleattr_list.value.forEach((element: any) => {
    const find = spuFormData.spuSaleAttrList.find((row) => {
      return row.id == element.id
    })
    if (find) {
      element.isShow = false
    } else {
      length++
      element.isShow = true
    }
  })
  select_saleAttr_length.value = length
  select_saleAttrIdd.value = ''
}
const initFileList = (data) => {
  if (data.length > 0) {
    fileList.value = data.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      }
    })
  } else {
    fileList.value = []
  }
}
let fileList = ref<UploadUserFile[]>([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const uploadCallback = (uploadFile) => {
  console.log(uploadFile)
}
const init_spuFormData = () => {
  Object.assign(spuFormData, {
    ...spuFormData_init,
    spuSaleAttrList: [],
  })
  console.log(spuFormData)
  initFileList([])
  trademark_list.value = []
  saleattr_list.value = []
}

const confirmClick = async () => {
  spuFormData.spuImageList = fileList.value.reduce((p: any, n: any) => {
    let IMG = {}
    if (n.response) {
      if (n.response.code == 200) {
        IMG['imgName'] = n.name
        IMG['imgUrl'] = n.response.data
      }
    } else {
      IMG['imgName'] = n.name
      IMG['imgUrl'] = n.url
    }
    p.push(IMG)
    return p
  }, [])
  let result: any = await reqAddOrUpdateSPU(spuFormData)
  let type = '添加'
  if (spuFormData.id) {
    type = '修改'
  }
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
    init_spuFormData()
    emit('confirmUpdate', spuFormData)
  } else {
    ElMessage({
      type: 'error',
      message: `${type}失败`,
    })
  }
}

const cancelClick = () => {
  init_spuFormData()
  emit('cancelUpdate')
}

const inputValue = ref('')
const InputRef = reactive({})

const handleClose = (arr, index) => {
  arr.splice(index, 1)
}

const showInput = (row, index) => {
  console.log(row, index)
  row.selected = true
  nextTick(() => {
    InputRef[index].focus()
  })
}

const handleInputConfirm = (row, index) => {
  console.log(row, index)
  if (inputValue.value) {
    row.supSaleAttrValueList.push({
      saleAttrName: row.saleAttrName,
      saleAttrValueName: inputValue.value,
    })
  }
  row.selected = false
  inputValue.value = ''
}

// // 删除对话框
const DELETE_ATTR = async (_row, index) => {
  const flag = await publicConfirm({
    title: '提示',
    content: '确认删除该属性？',
  })
  let type = '删除'
  if (flag) {
    spuFormData.spuSaleAttrList.splice(index, 1)
    initSaleAttrList()
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
  } else {
    ElMessage({
      type: 'info',
      message: `取消${type}`,
    })
  }
}

const ADD_ATTR_ROW = () => {
  const find: any = saleattr_list.value.find((attr: any) => {
    return attr.id == select_saleAttrIdd.value
  })
  if (find) {
    spuFormData.spuSaleAttrList.push({
      saleAttrName: find.name,
      id: find.id,
      supSaleAttrValueList: [],
    })
    initSaleAttrList()
  } else {
    return
  }
}
</script>

<style scoped lang="scss">
.tag_row {
  display: flex;
  align-items: center;
}
</style>
